package com.bawei.module_mine.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.lib_net.entity.ResponseEntity
import com.bawei.module_mine.intent.RegisterIntent
import com.bawei.module_mine.model.entity.UserEntity
import com.bawei.module_mine.model.service.UserCenterService
import com.bawei.module_mine.state.RegisterState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class RegisterViewModel :BaseViewModel<RegisterIntent>(){
    private val registerService by lazy {
        UserCenterService()
    }
    private val _state= MutableStateFlow<RegisterState>(RegisterState.registerInit)
    val state: StateFlow<RegisterState>
        get() = _state
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is RegisterIntent.register -> doRegisterIntent( it)
                }
            }
        }
    }
    private fun doRegisterIntent(it:RegisterIntent.register){
        viewModelScope.launch (Dispatchers.IO){
            try {
                Log.d("RegisterViewModel", "开始注册请求: username=${it.username}")
                val result: ResponseEntity<UserEntity> = registerService.register(it.username,it.password)
                
                withContext(Dispatchers.Main) {
                    if (result.code==200){
                        Log.d("RegisterViewModel", "注册成功")
                        _state.value = RegisterState.registerSuccess(result.data)
                    }else{
                        Log.d("RegisterViewModel", "注册失败: code=${result.code}, msg=${result.msg}")
                        _state.value = RegisterState.registerFailed(true)
                    }
                }
            } catch (e: Exception) {
                Log.e("RegisterViewModel", "注册请求异常: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    _state.value = RegisterState.registerFailed(true)
                }
            }
        }
    }
}